package com.vay.de.dang.online.web;

import com.vay.de.dang.online.util.VnHandler;

public abstract class WorkerBase implements Runnable {

    protected ReqCallback mCallback;

    public WorkerBase(ReqCallback callback) {
        mCallback = callback;
    }

    public void begin() {
        if (mCallback != null) {
            mCallback.start();
        }
    }

    public void end() {
        if (mCallback != null) {
            mCallback.end();
        }
    }

    @Override
    public void run() {
        VnHandler.runUI(this::begin);
        try {
            ReqResult result = doTask();
            if (result != null) {
                if (result.isOk()) {
                    VnHandler.runUI(() -> mCallback.callback(result));
                } else {
                    VnHandler.runUI(() -> mCallback.error(result));
                    VnHandler.showText(result.msg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            VnHandler.runUI(() -> mCallback.callback(ReqResult.error(e.toString())));
        }

        VnHandler.runUI(this::end);
    }

    public abstract ReqResult doTask() throws Exception;
}
